import React, { useRef, useState, useEffect, useCallback } from 'react';
import './VesselExtractionViewer.css';

const VesselExtractionViewer = ({ 
  data, 
  onMaskGenerated,
  onExitVesselMode
}) => {
  const canvasRef = useRef(null);
  const overlayCanvasRef = useRef(null);
  const containerRef = useRef(null);
  
  const [threshold, setThreshold] = useState(0.5);
  const [mipImage, setMipImage] = useState(null);
  const [maskData, setMaskData] = useState(null);
  const [viewport, setViewport] = useState({
    scale: 1,
    translation: { x: 0, y: 0 }
  });
  const [isDragging, setIsDragging] = useState(false);
  const [lastMousePos, setLastMousePos] = useState({ x: 0, y: 0 });
  const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
  const [stats, setStats] = useState({ vesselPixels: 0, totalPixels: 0 });

  // 监听容器大小变化
  useEffect(() => {
    const updateSize = () => {
      if (containerRef.current) {
        const rect = containerRef.current.getBoundingClientRect();
        setContainerSize({ width: rect.width, height: rect.height });
      }
    };

    const resizeObserver = new ResizeObserver(updateSize);
    if (containerRef.current) {
      resizeObserver.observe(containerRef.current);
    }

    updateSize();
    window.addEventListener('resize', updateSize);
    
    return () => {
      resizeObserver.disconnect();
      window.removeEventListener('resize', updateSize);
    };
  }, []);

  // 生成MIP图像（最大密度投影）
  const generateMIPImage = useCallback(async () => {
    if (!data || !data.images || data.images.length === 0) return;

    console.log('生成DSA取反的MIP图像...');
    
    const { images } = data;
    const firstImage = images[0];
    const { rows, columns } = firstImage;
    
    // 创建MIP数据数组
    const mipData = new Float32Array(rows * columns);
    mipData.fill(-Infinity);
    
    // 对每一帧图像进行处理
    for (const imageData of images) {
      try {
        let pixelData;
        
        // 提取像素数据
        if (imageData.dataSet && imageData.dataSet.pixelData) {
          pixelData = imageData.dataSet.pixelData;
        } else {
          console.warn('无法获取像素数据');
          continue;
        }
        
        // 对DSA图像进行反转并计算MIP
        for (let i = 0; i < pixelData.length && i < mipData.length; i++) {
          // DSA图像反转（假设16位数据）
          const invertedValue = 65535 - pixelData[i];
          // 取最大值投影
          if (invertedValue > mipData[i]) {
            mipData[i] = invertedValue;
          }
        }
      } catch (error) {
        console.error('处理图像帧失败:', error);
      }
    }
    
    // 归一化MIP数据到0-255范围
    let minVal = Infinity;
    let maxVal = -Infinity;
    for (let i = 0; i < mipData.length; i++) {
      if (mipData[i] !== -Infinity) {
        if (mipData[i] < minVal) minVal = mipData[i];
        if (mipData[i] > maxVal) maxVal = mipData[i];
      }
    }
    
    const range = maxVal - minVal;
    const normalizedData = new Uint8Array(mipData.length);
    for (let i = 0; i < mipData.length; i++) {
      if (mipData[i] === -Infinity) {
        normalizedData[i] = 0;
      } else {
        normalizedData[i] = range > 0 ? Math.round(((mipData[i] - minVal) / range) * 255) : 128;
      }
    }
    
    // 创建图像数据URL
    const canvas = document.createElement('canvas');
    canvas.width = columns;
    canvas.height = rows;
    const ctx = canvas.getContext('2d');
    
    const imageData = ctx.createImageData(columns, rows);
    const pixels = imageData.data;
    
    for (let i = 0; i < normalizedData.length; i++) {
      const gray = normalizedData[i];
      pixels[i * 4] = gray;     // Red
      pixels[i * 4 + 1] = gray; // Green
      pixels[i * 4 + 2] = gray; // Blue
      pixels[i * 4 + 3] = 255;  // Alpha
    }
    
    ctx.putImageData(imageData, 0, 0);
    
    const img = new Image();
    img.onload = () => {
      setMipImage(img);
      console.log(`MIP图像生成完成: ${columns}x${rows}`);
    };
    img.src = canvas.toDataURL();
    
    // 保存原始MIP数据用于阈值处理
    return { mipData: normalizedData, rows, columns };
  }, [data]);

  // 生成基于阈值的mask
  const generateMask = useCallback((mipData, rows, columns, thresholdValue) => {
    if (!mipData) return null;
    
    const thresholdGray = thresholdValue * 255;
    const mask = new Uint8Array(mipData.length);
    let vesselPixels = 0;
    
    for (let i = 0; i < mipData.length; i++) {
      if (mipData[i] > thresholdGray) {
        mask[i] = 255;
        vesselPixels++;
      } else {
        mask[i] = 0;
      }
    }
    
    setStats({
      vesselPixels,
      totalPixels: mipData.length
    });
    
    return mask;
  }, []);

  // 初始化时生成MIP图像
  useEffect(() => {
    let mipDataRef = null;
    
    const initMIP = async () => {
      const result = await generateMIPImage();
      if (result) {
        mipDataRef = result;
        const mask = generateMask(result.mipData, result.rows, result.columns, threshold);
        setMaskData(mask);
      }
    };
    
    initMIP();
    
    // 清理函数中保存引用以便后续使用
    return () => {
      if (mipDataRef) {
        window.currentMipData = mipDataRef;
      }
    };
  }, [data, generateMIPImage, generateMask, threshold]);

  // 当阈值改变时重新生成mask
  useEffect(() => {
    if (window.currentMipData) {
      const mask = generateMask(window.currentMipData.mipData, window.currentMipData.rows, window.currentMipData.columns, threshold);
      setMaskData(mask);
    }
  }, [threshold, generateMask]);

  // 绘制图像和mask叠加
  const drawImageWithMask = useCallback(() => {
    const canvas = canvasRef.current;
    const overlayCanvas = overlayCanvasRef.current;
    
    if (!canvas || !overlayCanvas || !mipImage || !containerSize.width || !containerSize.height) return;
    
    // 设置canvas尺寸
    canvas.width = containerSize.width;
    canvas.height = containerSize.height;
    overlayCanvas.width = containerSize.width;
    overlayCanvas.height = containerSize.height;
    
    const ctx = canvas.getContext('2d');
    const overlayCtx = overlayCanvas.getContext('2d');
    
    // 清空画布
    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    overlayCtx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
    
    // 计算图像显示位置和尺寸
    const imageAspect = mipImage.width / mipImage.height;
    const canvasAspect = canvas.width / canvas.height;
    
    let drawWidth, drawHeight;
    if (imageAspect > canvasAspect) {
      drawWidth = canvas.width * viewport.scale;
      drawHeight = drawWidth / imageAspect;
    } else {
      drawHeight = canvas.height * viewport.scale;
      drawWidth = drawHeight * imageAspect;
    }
    
    const x = (canvas.width - drawWidth) / 2 + viewport.translation.x;
    const y = (canvas.height - drawHeight) / 2 + viewport.translation.y;
    
    // 绘制MIP图像
    ctx.drawImage(mipImage, x, y, drawWidth, drawHeight);
    
    // 绘制mask叠加
    if (maskData && window.currentMipData) {
      const { rows, columns } = window.currentMipData;
      const maskCanvas = document.createElement('canvas');
      maskCanvas.width = columns;
      maskCanvas.height = rows;
      const maskCtx = maskCanvas.getContext('2d');
      
      const maskImageData = maskCtx.createImageData(columns, rows);
      const pixels = maskImageData.data;
      
      // 创建红色半透明mask
      for (let i = 0; i < maskData.length; i++) {
        if (maskData[i] > 0) {
          pixels[i * 4] = 255;     // Red
          pixels[i * 4 + 1] = 0;   // Green
          pixels[i * 4 + 2] = 0;   // Blue
          pixels[i * 4 + 3] = 100; // Alpha (半透明)
        } else {
          pixels[i * 4 + 3] = 0;   // 完全透明
        }
      }
      
      maskCtx.putImageData(maskImageData, 0, 0);
      
      // 叠加绘制mask
      overlayCtx.globalAlpha = 0.6;
      overlayCtx.drawImage(maskCanvas, x, y, drawWidth, drawHeight);
      overlayCtx.globalAlpha = 1.0;
    }
  }, [mipImage, maskData, viewport, containerSize]);

  // 绘制更新
  useEffect(() => {
    drawImageWithMask();
  }, [drawImageWithMask]);

  // 鼠标事件处理
  const handleMouseDown = (e) => {
    if (e.button === 0) { // 左键拖拽
      setIsDragging(true);
      setLastMousePos({ x: e.clientX, y: e.clientY });
    }
  };

  const handleMouseMove = (e) => {
    if (isDragging) {
      const deltaX = e.clientX - lastMousePos.x;
      const deltaY = e.clientY - lastMousePos.y;
      
      setViewport(prev => ({
        ...prev,
        translation: {
          x: prev.translation.x + deltaX,
          y: prev.translation.y + deltaY
        }
      }));
      
      setLastMousePos({ x: e.clientX, y: e.clientY });
    }
  };

  const handleMouseUp = () => {
    setIsDragging(false);
  };

  const handleWheel = (e) => {
    e.preventDefault();
    const scaleFactor = e.deltaY > 0 ? 0.9 : 1.1;
    setViewport(prev => ({
      ...prev,
      scale: Math.max(0.1, Math.min(5, prev.scale * scaleFactor))
    }));
  };

  // 重置视图
  const resetViewport = () => {
    setViewport({ scale: 1, translation: { x: 0, y: 0 } });
  };

  // 生成最终的血管mask
  const handleGenerateMask = () => {
    if (maskData && window.currentMipData) {
      const { rows, columns } = window.currentMipData;
      
      // 创建二值化mask数据
      const binaryMask = new Uint8Array(maskData.length);
      for (let i = 0; i < maskData.length; i++) {
        binaryMask[i] = maskData[i] > 0 ? 1 : 0;
      }
      
      const vesselMask = {
        mask: binaryMask,
        width: columns,
        height: rows,
        threshold: threshold,
        timestamp: Date.now(),
        stats: stats
      };
      
      console.log('血管mask生成完成:', vesselMask);
      onMaskGenerated && onMaskGenerated(vesselMask);
    }
  };

  return (
    <div className="vessel-extraction-viewer" ref={containerRef}>
      <div className="vessel-header">
        <h3>血管提取</h3>
        <button
          className="exit-vessel-btn"
          onClick={onExitVesselMode}
          title="退出血管提取模式"
        >
          <span className="exit-icon">←</span>
          <span className="exit-text">返回原始视图</span>
        </button>
      </div>
      
      <div className="vessel-content">
        {/* 左侧图像显示区域 */}
        <div className="vessel-image-panel">
          <div className="vessel-toolbar">
            <button onClick={resetViewport} className="tool-btn" title="适应窗口">
              🔍 适应
            </button>
            <span className="vessel-info">
              血管像素: {stats.vesselPixels} / {stats.totalPixels} 
              ({stats.totalPixels > 0 ? ((stats.vesselPixels / stats.totalPixels) * 100).toFixed(1) : 0}%)
            </span>
          </div>
          
          <div className="canvas-container">
            <canvas
              ref={canvasRef}
              className="vessel-canvas"
              style={{ position: 'absolute', zIndex: 1 }}
            />
            <canvas
              ref={overlayCanvasRef}
              className="vessel-overlay-canvas"
              style={{ position: 'absolute', zIndex: 2 }}
              onMouseDown={handleMouseDown}
              onMouseMove={handleMouseMove}
              onMouseUp={handleMouseUp}
              onMouseLeave={handleMouseUp}
              onWheel={handleWheel}
            />
          </div>
        </div>
        
        {/* 右侧控制面板 */}
        <div className="vessel-control-panel">
          <div className="control-header">
            <h4>阈值控制</h4>
          </div>
          
          <div className="control-content">
            <div className="threshold-control">
              <label>阈值设置:</label>
              <div className="threshold-slider-container">
                <input
                  type="range"
                  min="0"
                  max="1"
                  step="0.01"
                  value={threshold}
                  onChange={(e) => setThreshold(parseFloat(e.target.value))}
                  className="threshold-slider"
                />
                <span className="threshold-value">{(threshold * 100).toFixed(0)}%</span>
              </div>
            </div>
            
            <div className="threshold-presets">
              <label>快速设置:</label>
              <div className="preset-buttons">
                <button onClick={() => setThreshold(0.3)} className="preset-btn">30%</button>
                <button onClick={() => setThreshold(0.5)} className="preset-btn">50%</button>
                <button onClick={() => setThreshold(0.7)} className="preset-btn">70%</button>
              </div>
            </div>
            
            <div className="mask-info">
              <h5>分割统计:</h5>
              <div className="info-item">
                <span>血管像素:</span>
                <span>{stats.vesselPixels.toLocaleString()}</span>
              </div>
              <div className="info-item">
                <span>总像素:</span>
                <span>{stats.totalPixels.toLocaleString()}</span>
              </div>
              <div className="info-item">
                <span>血管比例:</span>
                <span>{stats.totalPixels > 0 ? ((stats.vesselPixels / stats.totalPixels) * 100).toFixed(2) : 0}%</span>
              </div>
            </div>
            
            <div className="mask-actions">
              <button
                className="generate-mask-btn"
                onClick={handleGenerateMask}
                disabled={!maskData}
              >
                <span className="btn-icon">✓</span>
                <span className="btn-text">确定生成血管Mask</span>
              </button>
              
              <div className="mask-description">
                生成的血管mask将用于后续的血管区域提取分析
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VesselExtractionViewer; 